package com.situ.company.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UpLoad {
    public static Map<String, Object> upload(HttpServletRequest req) throws FileUploadException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(req);

        List<String> names = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
                map.put(name, value);
            } else {
                String fn = getFName(item);
                FileOutputStream fw = new FileOutputStream(getFPath() + "/" + fn);
                byte[] b = new byte[1024 * 1024];
                int length = -1;
                InputStream is = item.getInputStream();
                while (-1 != (length = is.read(b))) {
                    fw.write(b, 0, length);
                }
                fw.flush();
                fw.close();
                is.close();
                names.add(fn);
            }
        }
        map.put("list", names);
        return map;
    }

    private static String getFName(FileItem item) {
        String fn = item.getName();
        fn = UUID.randomUUID().toString() + fn.substring(fn.indexOf("."));
        // System.currentTimeMillis()
        return fn;
    }

    private static File getFPath() {
        File f = new File("D:/StudySDUT/Java/images");
        if (!f.exists()) {
            f.mkdir();
        }
        return f;
    }
    
    public static void delFile(String filename) {
        File f = new File(getFPath() + "/" + filename);
        f.delete();
    }
}
